#!/usr/bin/env python

import unittest
import util
import sys

from CaseBase import CaseBase

## Class name should be same as file name for TestLoader to load
## This test suite is used for component test of ProfileRegistration profile
class CT_ProfileRegistration(CaseBase):
    ## Test case setup and teardown section
    def setUp(self):
        util.logEnter(self)
        
        self.rpInstList = self.wbemConnect.EnumerateInstances('CIM_RegisteredProfile')
        self.rspInstList = self.wbemConnect.EnumerateInstances('CIM_RegisteredSubProfile')
        
        util.logExit(self)
        
    def tearDown(self):
        util.logEnter(self)
        
        util.logExit(self)


    ## Test case section

    ## Tests to enumerate all the classes and associations involved
    ## in ProfileRegistration Profile
    def test_EnumerateAllClassesAndAssociations_Succeeds(self):
        """Enumerates all classes and associations in this profile."""
        
        util.logEnter(self)
        associationshipList = [
            ('CIM_RegisteredProfile', 'CIM_SubProfileRequiresProfile', 'CIM_RegisteredSubProfile'),
            ('CIM_RegisteredProfile', 'CIM_ElementConformsToProfile', 'CIM_ComputerSystem')]
        self.assertTrue(util.coverAllAssociationship(self.wbemConnect, associationshipList),
                        'Not all classes or associations can be enumerated.',
                        'All classes and associations can be enumerated.')
        
        util.logExit(self)

    ## Tests all the RegisteredSubProfile instances can be found
    ## in the instances of RegisteredProfile
    def test_SubProfileAllInProfile_Succeeds(self):
        """Tests all the SubProfile instances can be found in the instances of RegisteredProfile."""
        
        util.logEnter(self)
        for rspInst in self.rspInstList:
            self.assertTrue(rspInst in self.rpInstList,
                            'RegisteredSubProfile - <%s> cannot be found in RegisteredProfile List.'
                            % rspInst)
        print("""All the RegisteredSubProfile instances can be found """
              """in the instances of RegisteredProfile.""")
        util.logExit(self)

    
    def test_NASHeadComputerSystemConformsToProfile_Succeeds(self):
        """Tests the NAS Head Computer System conforms to Registered Profile."""
        util.logEnter(self)

        # Check the NAS head computer system confroms to RegisteredProfile
        csInstList = self.wbemConnect.EnumerateInstances('CIM_ComputerSystem')
        nasheadCSInstList = util.getInstancesWithProperty(
            self.wbemConnect.EnumerateInstances('CIM_ComputerSystem'), 'Dedicated', [24])

        self.assertTrue(len(nasheadCSInstList) == 1,
                        'There must be one and only one NAS head computer system.',
                        'The NAS Head is retrieved, %s' % util.detailInfo(nasheadCSInstList[0]))

        associatedRPList = util.queryAssociatedInstances(self.wbemConnect,
                                                         nasheadCSInstList[0],
                                                         'CIM_ElementConformsToProfile',
                                                         'CIM_RegisteredProfile')
        self.assertTrue(len(associatedRPList) == 1,
                        'The NAS Head computer system must be conformed to one RegisteredProfile.',
                        'The NAS Head computer system is conformed to one RegisteredProfile - %s'
                        % associatedRPList[0])

        # Check the NAS head computer system instance can be enumerated from RegisterdProfile
        nasHeadInstDict = {}
        for rpInstance in self.rpInstList:
            managedElementList = util.queryAssociatedInstances(self.wbemConnect,
                                                               rpInstance,
                                                               'CIM_ElementConformsToProfile',
                                                               'CIM_ComputerSystem')
            if len(managedElementList) != 0:
                nasheadCSInstList = util.getInstancesWithProperty(managedElementList,
                                                                  'Dedicated', [24])
                self.assertTrue(len(nasheadCSInstList) == 1,
                                """There should be only one computer system conforming to """
                                """RegisteredProfile - %s.""" % util.detailInfo(rpInstance))
                self.assertFalse(rpInstance in nasHeadInstDict,
                                 """There already exists some computer system """
                                 """conforming to this RegisteredProfile - %s."""
                                 % util.detailInfo(rpInstance))
                nasHeadInstDict[rpInstance] = nasheadCSInstList[0]
        self.assertTrue(len(nasHeadInstDict) != 0,
                        'The NAS head computer system must conform to one RegisterdProfile')
        for key in nasHeadInstDict:
            print('The NAS head computer system <%s> is enumerated from RegisteredProfile <%s>.'
                  % (nasHeadInstDict[key].classname, key.classname))
        
        util.logExit(self)
        

    # Tests the SubProfileRequiresProfile association
    def test_SubProfileRequiresProfile_Succeeds(self):
        """Tests the SubProfileRequiresProfile association."""
        
        util.logEnter(self)

        # Check that all SubProfiles are owned by RegisteredProfiles
        associatedRPDict = {}
        for rpInst in self.rpInstList:
            associatedRSPList = util.queryAssociatedInstances(self.wbemConnect,
                                                              rpInst,
                                                              'CIM_SubProfileRequiresProfile',
                                                              'CIM_RegisteredSubProfile')
            if len(associatedRSPList) != 0:
                self.assertFalse(rpInst in associatedRPDict,
                                'There already exists sub profile associated to profile - %s'
                                % util.detailInfo(rpInst))
                associatedRPDict[rpInst] = associatedRSPList
        allGotRSPList = []
        allGotRSPKeyList = []
        for key in associatedRPDict:
            allGotRSPList += associatedRPDict[key]
            allGotRSPKeyList.append(key)

        self.assertTrue(sorted(self.rspInstList) == sorted(allGotRSPList),
                        'All SubProfiles should be owned by RegisteredProfiles.',
                        'All SubProfiles are owned by RegisteredProfiles.')

        # Check that all RegisteredProfiles can be reached from SubProfiles
        associatedRSPDict = {}
        for rspInst in self.rspInstList:
            associatedRPList = util.queryAssociatedInstances(self.wbemConnect,
                                                             rspInst,
                                                             'CIM_SubProfileRequiresProfile',
                                                             'CIM_RegisteredProfile')
            if len(associatedRPList) != 0:
                self.assertFalse(rspInst in associatedRSPDict,
                                'There already exists profile associated to sub profile - {}'
                                .format(rspInst.classname))
                associatedRSPDict[rspInst] = associatedRPList

        allGotRPList = []
        for key in associatedRSPDict:
            for each in associatedRSPDict[key]:
                if not each in allGotRPList:
                    allGotRPList.append(each)

        self.assertTrue(sorted(allGotRPList) == sorted(allGotRSPKeyList),
                        'Not all RegisteredProfiles can be reached from SubProfiles.',
                        'All RegisteredProfiles can be reached from SubProfiles.')
                        
        util.logExit(self)
    
